import React, { useEffect, useState } from 'react'
import { NavBar, Icon, List } from 'antd-mobile'
import { getCountryData } from '../../api/common'
import './index.css'
const Item = List.Item
export default function Country(props) {

  const [countryData, setcountryData] = useState({})
  useEffect(async () => {
    const result = await getCountryData()
    // console.log(result.data.data)
    setcountryData(result.data.data)
  }, [])

  const keyList = Object.keys(countryData)

  // 索引跳转
  function linkHandle(e) {
    e.preventDefault();
    const id = e.target.innerText;  
    const ele = document.querySelector(id === "*" ? "#top" : `#${id}`);

     window.scrollTo({
       top: ele.offsetTop,
       behavior: "smooth",
     });

     
  }
  const changeNumHandle = (num) => (e) => {
    // console.log(num);
    localStorage.setItem('area-num', num)
    props.history.goBack()
  }

  return (
    <div className="country_wrap">
      {/* 头部 */}
      <div className="country_top">
        <NavBar
          mode="light"
          icon={<Icon type="left" color="black" />}
          onLeftClick={() => props.history.goBack()}
        >
          硅谷注册登录
        </NavBar>
      </div>
      {/* 索引列 */}
      <div className="key_list">
        {keyList.map((item) => {
          return (
            <a href="" key={item} onClick={linkHandle}>
              {item}
            </a>
          );
        })}
      </div>
      {/* 城市列表 */}
      <div className="country">
        {/* countryData是一个对象,对象中有多少个键值对,就渲染多少个List组件 */}
        {keyList.map((item) => {
          const countryList = countryData[item];
          return (
            <List
              id={item === "*" ? "top" : item}
              key={item}
              renderHeader={() => item}
              className="my-list"
            >
              {countryList.map((item) => {
                // item {国家名称: 区号}
                // console.log("这是获取value值",Object.values(item)[0]);
                const key = Object.keys(item)[0];
                return (
                  <Item
                    key={key}
                    extra={item[key]}
                    onClick={changeNumHandle(item[key])}
                  >
                    {key}
                  </Item>
                );
              })}
            </List>
          );
        })}
      </div>
    </div>
  );
}
